package team.zero.lemon.common.MQ.producer;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import team.zero.lemon.common.utils.JsonUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.jms.*;
import java.io.Serializable;
/**
 * @author liang
 * @description 队列消息生产者，发送消息到队列
 */
public abstract class BaseQueueProductor<T extends Serializable> {

    @Autowired
    @Qualifier("mqConnectionFactory")
    private ConnectionFactory connectionFactory;
    private MessageProducer producer; // MessageProducer：消息发送者
    private Connection connection = null;
    private Session session = null;

    @PostConstruct
    private void init() {
        try {
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(Boolean.TRUE, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createQueue(getQueueName());
            producer = session.createProducer(destination);
            producer.setDeliveryMode(DeliveryMode.PERSISTENT);
        } catch ( JMSException e ) {
            clearResource();
        }
    }
    private void clearResource() {
        if (producer != null) {
            try {
                producer.close();
            } catch ( JMSException e ) {
                e.printStackTrace();
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch ( JMSException e1 ) {
                e1.printStackTrace();
            }
        }
    }
    @PreDestroy
    private void end() {
        clearResource();
    }
    public  void send(T message)
    {
        try {
            TextMessage textMessage = session.createTextMessage(JsonUtils.ObjectToJson(message));
            producer.send(textMessage);
            session.commit();
        } catch ( JMSException e ) {
            e.printStackTrace();
        }
    }
    public abstract String getQueueName();
}
